﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel.Composition;
using System.IO;
using System.ComponentModel.Composition.Hosting;

namespace FrameWork.Plugin
{
    /// <summary>
    /// 为插件载入提供临时存储
    /// </summary>
    internal class PluginContainer<T> where T:IPlugin
    {
        /// <summary>
        /// 临时存储的插件列表
        /// </summary>
        [ImportMany(typeof(PluginClass))]
        internal IEnumerable<IPluginProvider<T>> PluginProviderList=null;

        /// <summary>
        /// 载入指定目录中的所有插件
        /// </summary>
        /// <param name="PluginDir">要载入插件的目录</param>
        internal PluginContainer(string PluginDir)
        {
            if(!(new DirectoryInfo(PluginDir).Exists))
                Directory.CreateDirectory(PluginDir);
            
            DirectoryCatalog Catalog = new DirectoryCatalog(PluginDir);
            CompositionContainer Container = new CompositionContainer(Catalog);
            Container.ComposeParts(this);
        }

    }
    /// <summary>
    /// 表示一个插件载入器
    /// </summary>
    public class PluginLoader<T>where T:IPlugin
    {

        /// <summary>
        /// 载入指定目录中的所有插件
        /// </summary>
        /// <param name="PluginDir">要载入插件的目录</param>
        public static void LoadPlugin(string PluginDir)
        {
            PluginContainer<T> Container=new PluginContainer<T>(PluginDir);
            foreach(IPluginProvider<T> Provider in Container.PluginProviderList)
            {
                PluginPool.RegisterPlugin(Provider.GetPlugins());
            }
        }

    }
}
